<?php
require $_SERVER['DOCUMENT_ROOT'].'/../_core/common.php';

//权限验证
if( Role::init() == false ){
	exit('没有权限');
}

$db = new DB();

$username = isset($_POST['username']) ? h($_POST['username']) : '';
$groupid = isset($_POST['groupid']) ? intval($_POST['groupid']) : 0;
$locked = 1;
$is_del = 1;
$created = time();
$updated = $created;

if( $groupid < 2 || $username == '' ){
	echo '<script>alert("参数有误！");window.history.go(-1);</script>';
	exit;
}

//检测重复
$user_sql = 'select id from users where username="'.$username.'" and is_del=1 limit 1';
$user_rs = $db->query($user_sql)->getOne();
if( $user_rs['id'] > 0 ){
	echo '<script>alert("添加失败，用户 '.$username.' 已存在！");window.history.go(-1);</script>';
	exit;
}

//查询是否为论坛会员
$uid = file_get_contents('http://bbs.zgqw.com/s_api/select_uid_by_username_oss.php?pw=zgqw_2013&username='.urlencode($username));
if( $uid < 1 ){
	echo '<script>alert("添加失败，用户 '.$username.' 不是论坛会员！");window.history.go(-1);</script>';
	exit;
}

$data=array('groupid'=>$groupid,
			'uid'=>$uid,
			'username'=>$username,
			'locked'=>$locked,
			'is_del'=>$is_del,
			'created'=>$created,
			'updated'=>$updated,
			);
$db->table('users')->insert($data)->run();
$insert_id = $db->getId();//获取刚刚插入的自增id

//查用户组权限
$group_operation_sql = 'select modelid from roles_group where groupid='.$groupid;
$group_operation_rs = $db->query($group_operation_sql)->getAll();
foreach( $group_operation_rs as $v ){
	//逐条插入用户权限表
	$data = array('uid'=>$uid,
				'modelid'=>$v['modelid'],
				'created'=>$created,
				'updated'=>$updated,
				);
	$db->table('roles_users')->insert($data)->run();
}

echo '<script>alert("添加成功！");window.location.href="/www/admin/role/user_lists.php";</script>';
exit;